package org.restorator.service.impl;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.restorator.entity.Order;
import org.restorator.service.JsonParser;

import java.io.Writer;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Snisar Bogdan.
 */
public class JsonParserImpl implements JsonParser {


    @Override
    public <E> E fromJson(String json, Class<E> type) {
        Gson g = new Gson();
        com.google.gson.JsonParser parser = new com.google.gson.JsonParser();
        JsonElement elem = parser.parse(json);
        JsonObject obj = elem.getAsJsonObject();
        JsonElement data = obj.get("data");
        if(data.isJsonArray()) {
            List<E> list = new ArrayList<>();
            list = g.fromJson(data,
                            new TypeToken<List<E>>() {
                            }.getType());
        } else {
            E element = g.fromJson(data, type);
        }

//        GsonBuilder b = new GsonBuilder();
//        b.registerTypeAdapter(Apple.class, new JsonDeserializer<Apple>() {
//            @Override
//            public Apple deserialize(JsonElement arg0, Type arg1,
//                                     JsonDeserializationContext arg2) throws JsonParseException {
//                JsonObject appleObj = arg0.getAsJsonObject();
//                Gson g = new Gson();
//                // Construct an apple (this shouldn't try to parse the seeds stuff
//                Apple a = g.fromJson(arg0, Apple.class);
//                List<Seed> seeds = null;
//                // Check to see if we were given a list or a single seed
//                if (appleObj.get("seeds").isJsonArray()) {
//                    // if it's a list, just parse that from the JSON
//                    seeds = g.fromJson(appleObj.get("seeds"),
//                            new TypeToken<List<Seed>>() {
//                            }.getType());
//                } else {
//                    // otherwise, parse the single seed,
//                    // and add it to the list
//                    Seed single = g.fromJson(appleObj.get("seeds"), Seed.class);
//                    seeds = new ArrayList<Seed>();
//                    seeds.add(single);
//                }
//                // set the correct seed list
//                a.setSeeds(seeds);
//                return a;
//            }
//        });

        return null;
    }

    @Override
    public <E> E fromJsonAsObject(String value, String obj, Class<E> type) {
        return null;
    }


}
